package com.atguigu.gmall.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.omg.PortableInterceptor.Interceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class AppFeignConfig {

/*    @Bean
    RequestInterceptor headerReqeustInterceptor(){
        RequestInterceptor interceptor = new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //得到上次的请求
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = requestAttributes.getRequest();
                //从前面的请求头里面获取核心信息
                String userId = request.getHeader("userId");
                String userTempId = request.getHeader("userTempId");
                requestTemplate.header("userId",userId);
                requestTemplate.header("userTempId",userTempId);
            }
        };
        return interceptor;
    }*/

    /**
     * feign的拦截器，每次远程发请求的时候，都会尝试给新的request带上新的请求头
     * @return
     */
    @Bean
    RequestInterceptor headerReqeustInterceptor(){
        return (requestTemplate)->{
            //得到上次的请求
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null){
                HttpServletRequest request = requestAttributes.getRequest();
                //从前面的请求头里面获取核心信息
                String userId = request.getHeader("userId");
                String userTempId = request.getHeader("userTempId");
                requestTemplate.header("userId",userId);
                requestTemplate.header("userTempId",userTempId);
            }
        };
    }
}
